<script setup>
  import { VueFinalModal,ModalsContainer, useModal, useModalSlot } from 'vue-final-modal'
  import Cropper from "./Cropper.vue";
  import {base64ImgtoFile} from "../../utils/index.js";

  const props = defineProps(['editor'])
  const emits = defineEmits(['save'])
  const editor = props.editor
  const { node } = editor.state.selection

  const { open, close } = useModal({
    // Open the modal or not when the modal was created, the default value is `false`.
    defaultModelValue: false,
    /**
     * If set `keepAlive` to `true`:
     * 1. The `displayDirective` will be set to `show` by default.
     * 2. The modal component will not be removed after the modal closed until you manually execute `destroy()`.
     */
    keepAlive: false,
    // `component` is optional and the default value is `<VueFinalModal>`.
    component: VueFinalModal,
    slots: {
      default: useModalSlot({
        component: Cropper,
        attrs: {
          options: {
            img: node.attrs.src || ''
          },
          save: (data) => {
            const file = base64ImgtoFile(data)
            const event = {
              target: {
                files: [file]
              }
            }
            emits('save', event)
          },
          close: hideModal
        }
      })
    },
    attrs: {
      // Bind props to the modal component (VueFinalModal in this case).
      clickToClose: false,
      escToClose: true,
      zIndexFn: () => {
        return 10000
      },
      // Bind events to the modal component (VueFinalModal in this case).
      onBeforeOpen() { /* on before open */ },
      onOpened() { /* on opened */ },
      onBeforeClose() { /* on before close */ },
      onClosed() { /* on closed */ },
    }
  })

  function showModal() {
    open()
  }
  function hideModal() {
    close()
  }
</script>

<template>
  <button @click="showModal">编辑图片</button>
  <ModalsContainer />
</template>

<style lang="less" scoped>

</style>